#include "Weapons.h"
#include "Configuration.h"


// Weapon class
void Weapon::Fire(Point startPosition,Point direction)
{
	if (counter != 0)
		return;

	Projectile projectile = Projectile(templateProjectile);
	projectile.SetPosition(startPosition,direction);
	//projectile.Initialise("models/laserBeam.3ds",startPosition,direction);
	projectiles.push_back(projectile);
	counter = reloadTime;
};

void Weapon::Display()
{
	//decrement counter
	if (counter >0)
		counter--;

	for (int i = 0 ; i < projectiles.size() ; i++)
	{
		projectiles[i].Display();
		
		//move beam
		projectiles[i].Move();

		//delete beams that are not alive
		if (!projectiles[i].IsAlive)
			projectiles.erase(projectiles.begin()+i);
	}
}

void Weapon::Initialise()
{
	reloadTime = 7;
	counter = 0;
	AimDirection.x = 1;
	AimDirection.y = 0;
	AimDirection.z = 0;
	templateProjectile = Projectile();
	templateProjectile.Initialise("models/laserBeam.3ds",Point(0,0,0),Point(0,0,0));
}

//Projectile class
void Projectile::Initialise(char *initFile, Point startPosition, Point direction)
{
	p_3dsFileName = initFile;
	this->LoadObjectMesh();	
	Position = startPosition;
	Direction = direction;
	hitBox.LoadAndInitialise("models/laserBeamHB.3ds",Position);
	Speed = 2;
	power = 1;	
	IsAlive = true;
	health = 1;
}

void Projectile::SetPosition(Point newPosition,Point newDirection)
{
	Position = newPosition;
	hitBox.moveToPosition(Position);
	hitBox.moveToPosition(Position);
	Direction = newDirection;
}

void Projectile::Display()
{
	if(!IsAlive)
		return;
	glPushMatrix();	
	glTranslatef(Position.x,Position.y,Position.z);
	glBegin(GL_TRIANGLES);
	for (int i = 0 ; i < polygon_qty ; i ++)
	{
		glVertex3f(pVertices[pPolygons[i].a].x,pVertices[pPolygons[i].a].y,pVertices[pPolygons[i].a].z);
		glVertex3f(pVertices[pPolygons[i].b].x,pVertices[pPolygons[i].b].y,pVertices[pPolygons[i].b].z);
		glVertex3f(pVertices[pPolygons[i].c].x,pVertices[pPolygons[i].c].y,pVertices[pPolygons[i].c].z);
	}
	glEnd();
	glPopMatrix();
};

bool Projectile::Move()
{
	Position.x += Direction.x*Speed*Config::GameSpeed;
	Position.y += Direction.y*Speed*Config::GameSpeed;
	Position.z += Direction.z*Speed*Config::GameSpeed;
	hitBox.moveToPosition(Position);

	if (Position.x > Config::TopRightCorner.x  ||
		Position.x < -Config::TopRightCorner.x ||
		Position.y > Config::TopRightCorner.y  ||
		Position.y < -Config::TopRightCorner.y)
	{
		IsAlive = false;
		health = 0;
		return false;
	}
	return true;
}